package com.hooper.login.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hooper.login.anno.AuthCheck;
import com.hooper.login.anno.TokenIgnore;
import com.hooper.login.constant.CommonConstant;
import com.hooper.login.entity.*;
import com.hooper.login.exception.BusinessException;
import com.hooper.login.service.UserService;
import com.hooper.login.util.JWTUtil;
import com.hooper.login.util.UserHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author Tim Hooper
 * @version 1.0
 * @time 2022/12/28/12:03
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Resource
    private UserService userService;

    @AuthCheck(isAdmin = true)
    @GetMapping("list")
    public Result getList() {
        return Result.ok(userService.list());
    }

    @AuthCheck(allowRoles = Roles.VIP)
    @GetMapping("vip/recommend")
    public Result getVipRecommend() {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getRole, Roles.VIP.getRole());
        List<User> list = userService.list(wrapper);
        return Result.ok(list);
    }

    @AuthCheck(exceptRoles = Roles.REGULAR)
    @GetMapping("one")
    public Result getOne(long id) {
        return Result.ok(userService.getById(id));
    }

    @TokenIgnore
    @PostMapping("register")
    public Result register(@RequestBody UserVo user) {
        if (StringUtils.isAnyBlank(user.getPassword(), user.getName())) throw new RuntimeException("null");
        User toDbUser = new User();
        BeanUtils.copyProperties(user, toDbUser);
        userService.save(toDbUser);
        return Result.ok();
    }

    @TokenIgnore
    @PostMapping("login")
    public Result login(@RequestBody UserVo user, HttpServletRequest request) throws BusinessException {
        if (StringUtils.isAnyBlank(user.getPassword(), user.getName())) throw new BusinessException("null error");
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getName, user.getName());
        User userInDb = userService.getOne(wrapper);
        if (userInDb == null) throw new BusinessException("No such user, please register or check ur passcode");
        UserDto userDto = new UserDto();
        BeanUtils.copyProperties(userInDb, userDto);
        String token = JWTUtil.getToken(userDto);
        request.setAttribute(CommonConstant.TOKEN_HEADER, token);

        UserHolder.setUser(userDto);
        return Result.ok(token);
    }
}
